package video.dali.service.impl;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import video.dali.common.dto.UserDto;
import video.dali.common.dto.UserLoginDto;
import video.dali.common.entity.User;
import video.dali.common.utils.SaltMD5Util;
import video.dali.mapper.UserMapper;
import video.dali.service.UserService;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;


    /**
     * 用户登录
     * @param userLoginDto
     */
    @Override
    public User login(UserLoginDto userLoginDto) {
        User user = userMapper.getByUsername(userLoginDto.getUsername());
        if (user == null) {
            user = new User();
            BeanUtils.copyProperties(userLoginDto, user);
            user.setCreateTime(LocalDateTime.now());
            String saltPassword = SaltMD5Util.md5Hex(user.getPassword());
            user.setPassword(saltPassword);
            userMapper.insert(user);
            return user;
        }
        String userLoginDtoPassword = SaltMD5Util.md5Hex(userLoginDto.getPassword());
        if (!Objects.equals(user.getPassword(), userLoginDtoPassword)) {
            return null;
        }
        return user;
    }


    /**
     * 删除用户
     * @param ids
     */
    @Override
    public void deleteByIds(List<Integer> ids) {
        userMapper.deleteByIds(ids);
    }


    /**
     * 根据username查询用户
     * @param username
     * @return
     */
    @Override
    public User list(String username) {
        return userMapper.getByUsername(username);
    }


    /**
     * 根据username删除用户
     * @param username
     * @return
     */
    @Override
    public void deleteByUsername(String username) {
        userMapper.deleteByUsername(username);
    }


    /**
     * 更新用户信息
     * @param userDto
     */
    @Override
    public void update(UserDto userDto) {
        User user = new User();
        BeanUtils.copyProperties(userDto, user);
        user.setUpdateTime(LocalDateTime.now());
        userMapper.update(user);
    }
}
